/*
 * Copyright (c) 2016- 2020 qolome.com Inc. All Rights Reserved.
 * ProjectName: qolome-knowledge
 * FileName: ConnectionPoll.java
 * Author: jiangfeng@qolome.com
 * Date: 2020/3/9 下午5:47
 * LastModified: 2020/03/09 17:47:09
 */

package com.qolome.knowledge.design.pattern.flyweight.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * @author Qolome
 * @version V1.0
 * @Description 连接池
 * @date 2020年 03月09日 17:47:07
 */
public class ConnectionPool {


    private Vector<Connection> pool;

    private int poolSize = 100;

    private String url = "jdbc:mysql://lcoalhost:3306/test";

    private String username = "root";
    private String password = "root";
    private String driverName = "com.mysql.jdbc.Driver";


    public ConnectionPool() {
        pool = new Vector<Connection>(poolSize);
        try {
            Class.forName(driverName);
            for (int i = 0; i < poolSize; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection() {

        if (pool.size() > 0) {
            Connection connection = pool.get(0);
            pool.remove(connection);
            return connection;
        }
        return null;
    }

    public synchronized void release(Connection connection) {
        pool.add(connection);
    }

}
